package com.zhouyu.service;

import com.zhouyu.dto.CommonPayOutDto;

import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor;
import org.springframework.batch.item.file.transform.DelimitedLineAggregator;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;

/**
 * @Description:将读取的对象写入数据源
 * SpringBatch同样给我们提供比如JpaItemWriter，FlatFileItemWriter，HibernateItemWriter，JdbcBatchItemWriter等
 */
@Service
public class AlipayFileWriter {

  FlatFileItemWriter<CommonPayOutDto> flatFileItemWriter;

  public AlipayFileWriter() {
    flatFileItemWriter = new FlatFileItemWriter();
  }

  public FlatFileItemWriter<CommonPayOutDto> writer(){
    flatFileItemWriter.setAppendAllowed(true);
    flatFileItemWriter.setShouldDeleteIfExists(true);
    flatFileItemWriter.setEncoding("UTF-8");
    flatFileItemWriter.setResource(new FileSystemResource("./data/out/sample-data.txt"));
    flatFileItemWriter.setLineAggregator(new DelimitedLineAggregator<CommonPayOutDto>() {{
      setDelimiter(",");
      setFieldExtractor(new BeanWrapperFieldExtractor<CommonPayOutDto>() {{
        setNames(new String[]{"tranId", "channel", "tranType", "counterparty", "goods", "amount", "isDebitCredit", "state", "tranDate", "merId" });
      }});
    }});
    return flatFileItemWriter;
  }

}
